package com.getpebble.android.main.sections.mypebble.fragment;

import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblContentProviderUtil;
import com.getpebble.android.common.framework.widget.AsyncImageView;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.FrameworkState.EventType;
import com.getpebble.android.common.model.IWatchApp;
import com.getpebble.android.common.model.LoadedApp;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblInstalledAppDataModel;
import com.getpebble.android.common.model.SideloadApp;
import com.getpebble.android.framework.FrameworkEventReceiver;
import com.getpebble.android.framework.FrameworkEventReceiver.IFrameworkEventListener;
import com.getpebble.android.framework.PblFrameworkInterface;
import com.getpebble.android.framework.endpoint.InstallAppEndpoint.AppInstallResult;
import com.getpebble.android.framework.protocol.inbound.PblInboundAppResultInstallMessage.AppRemoveResult;
import com.getpebble.android.jskit.bridge.JsAppLifecycleListener;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.main.fragment.FragmentMetaData.FragmentType;
import com.getpebble.android.main.sections.appstore.constants.AppStoreConstants.StoreType;
import com.getpebble.android.main.sections.appstore.fragment.NoConnectivityFragment;
import com.getpebble.android.util.HttpUtils;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;

public class LoadUnloadDialogFragment extends DialogFragment {
    private static final String TAG = LoadUnloadDialogFragment.class.getSimpleName();
    private TextView mAppBy;
    private TextView mAppDesc;
    private AsyncImageView mAppIcon;
    private LinearLayout mAppInfoWrapper;
    private TextView mAppLabel;
    private View mBackgroundView;
    private View mDeleteContainer;
    private View mDeleteIcon;
    private OnClickListener mDeleteOnClickListener = new OnClickListener() {
        public void onClick(View v) {
            MobileAppBehavior.logButtonTapped("delete", "MyPebblePopup");
            if (LoadUnloadDialogFragment.this.mDeleteText.getVisibility() != 0) {
                LoadUnloadDialogFragment.this.mDeleteText.setVisibility(0);
                return;
            }
            Trace.debug(LoadUnloadDialogFragment.TAG, "Deleting watchapp option clicked");
            LoadUnloadDialogFragment.this.mRightButton.setEnabled(false);
            LoadUnloadDialogFragment.this.setCancelable(false);
            if (!(LoadUnloadDialogFragment.this.mIsPebbleFull || LoadUnloadDialogFragment.this.isAppUpdating())) {
                LoadUnloadDialogFragment.this.mSwitcher.showNext();
            }
            LoadUnloadDialogFragment.this.mLoadingText.setText(R.string.load_unload_deleting);
            LoadUnloadDialogFragment.this.hideDeleteOptionAnimated();
            MobileAppBehavior.logMyPebbleDetailsDeleteAppTapped();
            LoadUnloadDialogFragment.this.deleteWatchApp();
        }
    };
    private TextView mDeleteText;
    private int mDialogHeight;
    private PblFrameworkInterface mFrameworkInterface;
    private boolean mIsLoadingUnloading = false;
    private boolean mIsPebbleFull = false;
    private View mLeftButton;
    private TextView mLeftButtonText;
    private IFrameworkEventListener mListener;
    private TextView mLoadingText;
    private View mRightButton;
    private TextView mRightButtonText;
    private LoadUnloadState mState;
    private ViewSwitcher mSwitcher;
    private IWatchApp mWatchApp;
    private AsyncImageView mWatchImgOverlay;

    static /* synthetic */ class AnonymousClass16 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult = new int[AppInstallResult.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppResultInstallMessage$AppRemoveResult = new int[AppRemoveResult.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.SUCCESS.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.ERROR_BANK_FULL.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.ERROR_BUNDLE_DOWNLOAD.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.ERROR_NO_CONNECTED_DEVICE.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.ERROR_SDK_INCOMPATIBLE.ordinal()] = 5;
            } catch (NoSuchFieldError e5) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.ERROR_PRF.ordinal()] = 6;
            } catch (NoSuchFieldError e6) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppResultInstallMessage$AppRemoveResult[AppRemoveResult.SUCCESS.ordinal()] = 1;
            } catch (NoSuchFieldError e7) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppResultInstallMessage$AppRemoveResult[AppRemoveResult.NOT_CONNECTED.ordinal()] = 2;
            } catch (NoSuchFieldError e8) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppResultInstallMessage$AppRemoveResult[AppRemoveResult.IN_PRF.ordinal()] = 3;
            } catch (NoSuchFieldError e9) {
            }
        }
    }

    public enum LoadUnloadState {
        LOADING,
        UNLOADING
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(2, R.style.LoadUnloadDialog);
        this.mFrameworkInterface = PebbleApplication.getFrameworkInterface();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            this.mState = LoadUnloadState.valueOf(savedInstanceState.getString("STATE"));
            this.mWatchApp = (IWatchApp) savedInstanceState.getParcelable("WATCHAPP");
        }
        View view = inflater.inflate(R.layout.dialog_fragment_load_unload, container, false);
        view.findViewById(R.id.root_dlg).setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (LoadUnloadDialogFragment.this.isCancelable()) {
                    LoadUnloadDialogFragment.this.dismiss();
                }
            }
        });
        this.mBackgroundView = view.findViewById(R.id.background_view);
        this.mBackgroundView.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
            public boolean onPreDraw() {
                LoadUnloadDialogFragment.this.mDialogHeight = LoadUnloadDialogFragment.this.mBackgroundView.getMeasuredHeight();
                if (LoadUnloadDialogFragment.this.mDialogHeight != 0) {
                    LoadUnloadDialogFragment.this.mBackgroundView.getViewTreeObserver().removeOnPreDrawListener(this);
                    LoadUnloadDialogFragment.this.mBackgroundView.getLayoutParams().height = 0;
                    LoadUnloadDialogFragment.this.mBackgroundView.requestLayout();
                    LoadUnloadDialogFragment.this.mBackgroundView.setVisibility(4);
                }
                return false;
            }
        });
        this.mBackgroundView.setVisibility(0);
        final ImageView watchImage = (ImageView) view.findViewById(R.id.watch_image);
        this.mWatchImgOverlay = (AsyncImageView) view.findViewById(R.id.watch_image_overlay);
        watchImage.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
            public boolean onPreDraw() {
                watchImage.getViewTreeObserver().removeOnPreDrawListener(this);
                int width = watchImage.getWidth();
                int height = watchImage.getHeight();
                int heightOfIcon = (int) (((float) height) * 0.6f);
                int widthOfIcon = (int) (((float) heightOfIcon) * 0.85714287f);
                int leftMargin = (int) (0.14090909f * ((float) width));
                int topMargin = (int) (0.20714286f * ((float) height));
                LayoutParams params = (LayoutParams) LoadUnloadDialogFragment.this.mWatchImgOverlay.getLayoutParams();
                params.height = heightOfIcon;
                params.width = widthOfIcon;
                params.setMargins(leftMargin, topMargin, 0, 0);
                LoadUnloadDialogFragment.this.mWatchImgOverlay.requestLayout();
                LoadUnloadDialogFragment.this.mWatchImgOverlay.setVisibility(0);
                return true;
            }
        });
        this.mAppIcon = (AsyncImageView) view.findViewById(R.id.app_icon);
        this.mAppInfoWrapper = (LinearLayout) view.findViewById(R.id.app_info_wrapper);
        this.mAppLabel = (TextView) view.findViewById(R.id.app_label);
        this.mAppBy = (TextView) view.findViewById(R.id.app_by);
        this.mAppDesc = (TextView) view.findViewById(R.id.app_desc);
        this.mAppDesc.setMovementMethod(new ScrollingMovementMethod());
        this.mSwitcher = (ViewSwitcher) view.findViewById(R.id.switcher);
        this.mRightButton = view.findViewById(R.id.right_button);
        this.mRightButtonText = (TextView) view.findViewById(R.id.button_text_right);
        this.mLeftButton = view.findViewById(R.id.left_button);
        this.mLeftButtonText = (TextView) view.findViewById(R.id.button_text_left);
        this.mLoadingText = (TextView) view.findViewById(R.id.loading_text);
        this.mDeleteContainer = view.findViewById(R.id.delete_container);
        this.mDeleteText = (TextView) view.findViewById(R.id.delete_text);
        this.mDeleteIcon = view.findViewById(R.id.delete_icon);
        populateUiFromWatchApp();
        setupButtons();
        return view;
    }

    public void onDestroyView() {
        if (this.mListener != null) {
            FrameworkEventReceiver.unregisterFrameworkStateEventListener(this.mListener);
        }
        super.onDestroyView();
    }

    public void onSaveInstanceState(Bundle outState) {
        outState.putString("STATE", this.mState.toString());
        outState.putParcelable("WATCHAPP", this.mWatchApp);
        super.onSaveInstanceState(outState);
    }

    public void setWatchApp(IWatchApp watchApp) {
        this.mWatchApp = watchApp;
        setLoadUnloadState(this.mWatchApp.isLoaded() ? LoadUnloadState.UNLOADING : LoadUnloadState.LOADING);
    }

    private void setLoadUnloadState(LoadUnloadState state) {
        this.mState = state;
    }

    private void setupButtons() {
        if (this.mState.equals(LoadUnloadState.LOADING)) {
            if (isAppUpdating()) {
                this.mRightButtonText.setText(R.string.load_unload_update);
            } else {
                this.mRightButtonText.setText(R.string.load_unload_load);
            }
            this.mRightButtonText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_load, 0, 0, 0);
            this.mRightButton.setVisibility(0);
            this.mRightButton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    MobileAppBehavior.logButtonTapped("load", "MyPebblePopup");
                    MobileAppBehavior.logMyPebbleDetailsLoadTapped(LoadUnloadDialogFragment.this.mWatchApp);
                    LoadUnloadDialogFragment.this.mRightButton.setEnabled(false);
                    LoadUnloadDialogFragment.this.setCancelable(false);
                    LoadUnloadDialogFragment.this.mLoadingText.setText(R.string.load_unload_loading);
                    LoadUnloadDialogFragment.this.mSwitcher.showNext();
                    LoadUnloadDialogFragment.this.loadWatchApp();
                }
            });
            return;
        }
        this.mRightButtonText.setText(R.string.load_unload_unload);
        this.mRightButtonText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_unload, 0, 0, 0);
        this.mRightButton.setVisibility(0);
        this.mRightButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                MobileAppBehavior.logMyPebbleDetailsUnloadTapped(LoadUnloadDialogFragment.this.mWatchApp);
                LoadUnloadDialogFragment.this.mRightButton.setEnabled(false);
                LoadUnloadDialogFragment.this.setCancelable(false);
                LoadUnloadDialogFragment.this.mLoadingText.setText(R.string.load_unload_unloading);
                LoadUnloadDialogFragment.this.mSwitcher.showNext();
                LoadUnloadDialogFragment.this.unloadWatchApp(false);
            }
        });
        if ((this.mWatchApp instanceof LoadedApp) && ((LoadedApp) this.mWatchApp).isConfigurable()) {
            this.mLeftButton.setVisibility(0);
            this.mLeftButtonText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_settings, 0, 0, 0);
            this.mLeftButtonText.setText(R.string.load_unload_settings);
            this.mLeftButton.setOnClickListener(new OnClickListener() {
                public void onClick(View view) {
                    LoadUnloadDialogFragment.this.dismiss();
                    MobileAppBehavior.logMyPebbleDetailsConfigSettingsTapped((LoadedApp) LoadUnloadDialogFragment.this.mWatchApp);
                    Activity activity = LoadUnloadDialogFragment.this.getActivity();
                    if (activity == null) {
                        Trace.error(LoadUnloadDialogFragment.TAG, "WatchApp Settings: Activity was null");
                    } else if (HttpUtils.hasInternetConnection(activity.getApplicationContext())) {
                        JsAppLifecycleListener.onConfigLaunchRequest(activity, LoadUnloadDialogFragment.this.mWatchApp.getUuid());
                    } else {
                        NoConnectivityFragment noConnectivityFragment = new NoConnectivityFragment();
                        noConnectivityFragment.configureRefreshToStartWebApp(activity, LoadUnloadDialogFragment.this.mWatchApp.getUuid());
                        ((MainActivity) activity).switchFragment(noConnectivityFragment, false, false, true);
                    }
                }
            });
        }
    }

    private void showUninstallResult(AppRemoveResult removeResult, boolean isDelete) {
        setCancelable(true);
        int unloadingMsgId = R.string.load_unload_unload_fail;
        int unloadingMsgColor = 17170444;
        switch (AnonymousClass16.$SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundAppResultInstallMessage$AppRemoveResult[removeResult.ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                unloadingMsgId = isDelete ? R.string.load_unload_deleted : R.string.load_unload_unloaded;
                unloadingMsgColor = isDelete ? R.color.red : R.color.alert_result_text_color;
                break;
            case SMTPMessage.RETURN_HDRS /*2*/:
                showErrorDialog(R.string.load_unload_could_not_unload, R.string.load_unload_not_connected);
                break;
            case ListInfo.INDETERMINATE /*3*/:
                showErrorDialog(R.string.load_unload_could_not_unload, R.string.load_unload_fail_prf);
                break;
        }
        this.mLoadingText.setText(unloadingMsgId);
        this.mLoadingText.setTextColor(getResources().getColor(unloadingMsgColor));
        setupDelayedDismissal();
    }

    private void showInstallResult(AppInstallResult result) {
        setCancelable(true);
        int loadingMsgId = R.string.load_unload_install_fail;
        int loadingMsgColor = 17170444;
        switch (AnonymousClass16.$SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[result.ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                loadingMsgId = R.string.load_unload_load_success;
                loadingMsgColor = R.color.alert_result_text_color;
                break;
            case SMTPMessage.RETURN_HDRS /*2*/:
                loadingMsgId = R.string.load_unload_pebble_full;
                break;
            case ListInfo.INDETERMINATE /*3*/:
                showErrorDialog(R.string.load_unload_could_not_load, R.string.load_unload_download_failed);
                break;
            case SMTPMessage.NOTIFY_DELAY /*4*/:
                showErrorDialog(R.string.load_unload_could_not_load, R.string.load_unload_not_connected);
                break;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                showErrorDialog(R.string.load_unload_cannot_install_app, R.string.load_unload_need_to_update_fw_to_install);
                break;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsBackground /*6*/:
                showErrorDialog(R.string.load_unload_could_not_load, R.string.load_unload_fail_prf);
                break;
        }
        this.mLoadingText.setText(loadingMsgId);
        this.mLoadingText.setTextColor(getResources().getColor(loadingMsgColor));
        setupDelayedDismissal();
    }

    private void setupDelayedDismissal() {
        View rootView = getView();
        if (rootView == null) {
            dismiss();
        } else {
            rootView.postDelayed(new Runnable() {
                public void run() {
                    if (LoadUnloadDialogFragment.this.isVisible()) {
                        LoadUnloadDialogFragment.this.dismissAllowingStateLoss();
                    }
                }
            }, 1500);
        }
    }

    public void setIsPebbleFull(boolean isPebbleFull) {
        this.mIsPebbleFull = isPebbleFull;
    }

    private void populateUiFromWatchApp() {
        if (this.mWatchApp != null) {
            this.mAppLabel.setText(this.mWatchApp.getAppName());
            this.mAppBy.setText(this.mWatchApp.getCompanyName());
            this.mAppInfoWrapper.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    MobileAppBehavior.logButtonTapped("app_by_developer", "MyPebblePopup");
                    if (LoadUnloadDialogFragment.this.mWatchApp.getDeveloperId() != null && LoadUnloadDialogFragment.this.getActivity() != null && (LoadUnloadDialogFragment.this.getActivity() instanceof MainActivity)) {
                        LoadUnloadDialogFragment.this.dismiss();
                        MainActivity mainActivity = (MainActivity) LoadUnloadDialogFragment.this.getActivity();
                        Bundle args = new Bundle();
                        args.putInt("extra_store_type", StoreType.DEVELOPER_APPS.ordinal());
                        args.putString("extra_page_id", LoadUnloadDialogFragment.this.mWatchApp.getDeveloperId());
                        mainActivity.switchFragmentByType(FragmentType.APP_STORE_DEVELOPER, args);
                    }
                }
            });
            this.mAppDesc.setText(this.mWatchApp.getDescription());
            this.mWatchImgOverlay.fetch(this.mWatchApp.getPreviewImage());
            this.mAppIcon.fetch(this.mWatchApp.getIconImage());
            if (this.mIsPebbleFull && !isAppUpdating()) {
                this.mLoadingText.setText(R.string.load_unload_pebble_full);
                this.mSwitcher.showNext();
            }
            this.mDeleteText.setOnClickListener(this.mDeleteOnClickListener);
            this.mDeleteIcon.setOnClickListener(this.mDeleteOnClickListener);
        }
    }

    private void hideDeleteOption() {
        if (this.mDeleteContainer != null && this.mDeleteContainer.getVisibility() == 0) {
            this.mDeleteText.setVisibility(4);
            this.mDeleteContainer.setVisibility(8);
        }
    }

    private boolean isAppUpdating() {
        Activity activity = getActivity();
        if (activity == null) {
            Trace.error(TAG, "isUpdating: activity was null");
            return false;
        }
        PblDevice connectedDevice = PebbleApplication.getConnectedDevice();
        if (connectedDevice == null) {
            Trace.debug(TAG, "connectedDevice is null");
            return false;
        }
        String installingUUID = this.mWatchApp.getUuid().toString();
        Cursor cursor = PblInstalledAppDataModel.fetchInstalledApps(activity.getApplicationContext().getContentResolver(), connectedDevice);
        if (cursor == null) {
            return false;
        }
        while (cursor.moveToNext()) {
            if (cursor.getString(cursor.getColumnIndex("uuid")).equalsIgnoreCase(installingUUID)) {
                cursor.close();
                return true;
            }
        }
        cursor.close();
        return false;
    }

    private void hideDeleteOptionAnimated() {
        if (this.mDeleteContainer != null && this.mDeleteContainer.getVisibility() == 0) {
            this.mDeleteText.setVisibility(4);
            Animation animation = new TranslateAnimation(1, 0.0f, 1, 0.0f, 1, 0.0f, 1, 1.0f);
            animation.setAnimationListener(new AnimationListener() {
                public void onAnimationStart(Animation animation) {
                }

                public void onAnimationEnd(Animation animation) {
                    LoadUnloadDialogFragment.this.mDeleteContainer.setVisibility(8);
                }

                public void onAnimationRepeat(Animation animation) {
                }
            });
            animation.setDuration(1000);
            this.mDeleteContainer.startAnimation(animation);
        }
    }

    private void loadWatchApp() {
        hideDeleteOption();
        this.mListener = new IFrameworkEventListener() {
            public void onFrameworkStateChanged(FrameworkState newState) {
                if (newState.getLastEvent() != null && newState.getLastEvent().equals(EventType.APP_INSTALL_COMPLETE)) {
                    LoadUnloadDialogFragment.this.mIsLoadingUnloading = false;
                    int result = newState.getAppInstallResult();
                    Trace.debug(LoadUnloadDialogFragment.TAG, "App install result: " + result);
                    if (LoadUnloadDialogFragment.this.getActivity() != null) {
                        LoadUnloadDialogFragment.this.showInstallResult(AppInstallResult.fromValue(result));
                    }
                    FrameworkEventReceiver.unregisterFrameworkStateEventListener(LoadUnloadDialogFragment.this.mListener);
                } else if (newState.getLastEvent() == null || !newState.getLastEvent().equals(EventType.APP_INSTALL_PROGRESS_CHANGED)) {
                    Trace.debug(LoadUnloadDialogFragment.TAG, "Other event: " + newState.getLastEvent());
                } else {
                    int percentage = newState.getAppInstallProgress();
                    Trace.debug(LoadUnloadDialogFragment.TAG, "Install progress: " + percentage);
                    if (LoadUnloadDialogFragment.this.getActivity() != null) {
                        LoadUnloadDialogFragment.this.animateAppLoading(percentage);
                    }
                }
            }
        };
        if (this.mWatchApp.getPbwFile() != null) {
            Uri uri = Uri.parse(this.mWatchApp.getPbwFile());
            boolean allowReinstall = this.mWatchApp instanceof SideloadApp;
            PblDevice pblDevice = PebbleApplication.getConnectedDevice();
            if (pblDevice == null) {
                showInstallResult(AppInstallResult.ERROR_NO_CONNECTED_DEVICE);
                return;
            } else if (this.mIsLoadingUnloading) {
                Trace.warning(TAG, "Attempting to start load while loading");
                return;
            } else {
                FrameworkEventReceiver.registerFrameworkStateEventListener(this.mListener);
                Trace.debug(TAG, "Installing app");
                this.mIsLoadingUnloading = true;
                MobileAppBehavior.logAppInstallDetected(this.mWatchApp);
                this.mFrameworkInterface.installApp(pblDevice, uri, true, allowReinstall);
                return;
            }
        }
        Trace.error(TAG, "Unable to install app: no pbw file!");
        showInstallResult(AppInstallResult.ERROR_BUNDLE_DOWNLOAD);
    }

    private void unloadWatchApp(final boolean isDelete) {
        if (!isDelete) {
            animateAppUnload();
            hideDeleteOption();
        }
        this.mListener = new IFrameworkEventListener() {
            public void onFrameworkStateChanged(FrameworkState newState) {
                if (newState.getLastEvent() == null || !newState.getLastEvent().equals(EventType.APP_REMOVE_COMPLETE)) {
                    Trace.debug(LoadUnloadDialogFragment.TAG, "Other event: " + newState.getLastEvent());
                    return;
                }
                LoadUnloadDialogFragment.this.mIsLoadingUnloading = false;
                AppRemoveResult removeResult = AppRemoveResult.fromKey(newState.getAppRemoveResult());
                Trace.debug(LoadUnloadDialogFragment.TAG, "App remove result: " + removeResult);
                if (LoadUnloadDialogFragment.this.getActivity() != null) {
                    LoadUnloadDialogFragment.this.showUninstallResult(removeResult, isDelete);
                }
                FrameworkEventReceiver.unregisterFrameworkStateEventListener(LoadUnloadDialogFragment.this.mListener);
            }
        };
        PblDevice device = PebbleApplication.getConnectedDevice();
        if (device == null) {
            showUninstallResult(AppRemoveResult.NOT_CONNECTED, isDelete);
        } else if (this.mIsLoadingUnloading) {
            Trace.warning(TAG, "Attempting to start unload while unloading");
        } else {
            Trace.debug(TAG, "Trying to uninstall " + this.mWatchApp.getAppName() + " from " + device);
            FrameworkEventReceiver.registerFrameworkStateEventListener(this.mListener);
            this.mIsLoadingUnloading = true;
            this.mFrameworkInterface.uninstallApp(device, this.mWatchApp.getUuid().toString());
        }
    }

    private void deleteWatchApp() {
        Trace.debug(TAG, "Deleting watchApp: " + this.mWatchApp.getAppName());
        Trace.debug(TAG, "Showing app removal");
        animateAppRemoval();
        Activity activity = getActivity();
        if (activity != null) {
            String[] selectionArgs = new String[]{this.mWatchApp.getId()};
            ContentValues contentValues = new ContentValues();
            contentValues.put("_needs_delete", Integer.valueOf(1));
            int updated = activity.getContentResolver().update(PblContentProviderUtil.getTableUri("locker_apps"), contentValues, "app_id = ?", selectionArgs);
            if (updated != 1) {
                Trace.warning(TAG, "Unexpected number of rows updated: " + updated);
            }
            PebbleApplication.getSyncManager().syncLockerApps();
            MobileAppBehavior.logMyPebbleDetailsDeleteAppConfirmedEvent(this.mWatchApp);
        }
        if (this.mWatchApp.isLoaded()) {
            Trace.debug(TAG, "Unloading watchApp: " + this.mWatchApp.getAppName());
            unloadWatchApp(true);
            return;
        }
        this.mLoadingText.setText(R.string.load_unload_deleted);
        this.mLoadingText.setTextColor(getResources().getColor(R.color.red));
        setCancelable(true);
        setupDelayedDismissal();
    }

    private void animateAppLoading(int percentage) {
        this.mBackgroundView.setVisibility(0);
        this.mBackgroundView.setBackgroundColor(getResources().getColor(R.color.load_animation_color));
        int height = (this.mDialogHeight * percentage) / 100;
        final ValueAnimator valueAnimator = ValueAnimator.ofInt(new int[]{this.mBackgroundView.getLayoutParams().height, height});
        valueAnimator.addUpdateListener(new AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                LoadUnloadDialogFragment.this.mBackgroundView.getLayoutParams().height = ((Integer) valueAnimator.getAnimatedValue()).intValue();
                LoadUnloadDialogFragment.this.mBackgroundView.requestLayout();
            }
        });
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.start();
    }

    private void animateAppRemoval() {
        animateShrinkingBackground(R.color.transparent_red);
    }

    private void animateAppUnload() {
        animateShrinkingBackground(R.color.load_animation_color);
    }

    private void animateShrinkingBackground(int colorId) {
        LayoutParams params = (LayoutParams) this.mBackgroundView.getLayoutParams();
        params.addRule(12, -1);
        params.addRule(10, 0);
        params.height = this.mDialogHeight;
        this.mBackgroundView.setBackgroundColor(getResources().getColor(colorId));
        this.mBackgroundView.setVisibility(0);
        this.mBackgroundView.requestLayout();
        ValueAnimator valueAnimator = ValueAnimator.ofInt(new int[]{this.mBackgroundView.getLayoutParams().height, 0});
        valueAnimator.addUpdateListener(new AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                LoadUnloadDialogFragment.this.mBackgroundView.getLayoutParams().height = ((Integer) valueAnimator.getAnimatedValue()).intValue();
                LoadUnloadDialogFragment.this.mBackgroundView.requestLayout();
            }
        });
        valueAnimator.setDuration(1000);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.start();
    }

    private void showErrorDialog(final int titleResId, final int msgResId) {
        if (getActivity() != null && isAdded()) {
            DialogFragment errorDialog = new DialogFragment() {
                public Dialog onCreateDialog(Bundle savedInstanceState) {
                    return new Builder(getActivity()).setPositiveButton(17039370, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setTitle(titleResId).setMessage(msgResId).create();
                }
            };
            try {
                Activity activity = getActivity();
                if (activity == null) {
                    Trace.error(TAG, "showErrorDialog: Activity was null");
                } else {
                    errorDialog.show(activity.getFragmentManager(), "error_dialog");
                }
            } catch (IllegalStateException e) {
                Trace.error(TAG, "Exception when trying to show errorDialog");
            }
        }
    }
}
